import { createConnection, DataSource, getConnection, getRepository, Repository } from "typeorm";
import { IDBBase } from "../interfaces/IBase.interface";

export class DBBase{
    protected async Connection(dbname:string = "default"):Promise<DataSource>{
        let con:DataSource;
        try{
            con =  getConnection(dbname);
            if(con.isConnected){

            }else{
                con = await createConnection(dbname);
            }
        }catch(e){
            // console.error(e);
            con = await createConnection(dbname);
        }
        return con;
    }

    protected async Repository(entities:IDBBase<any>,dbname:string="default"):Promise<Repository<any>>{
        try{
            let con = getConnection(dbname);
            if(con.isConnected){
                const rep = getRepository(entities.entities,dbname);
                return rep;
            }else{
                // await this.Connection(dbname);
                // return await this.Repository(entities,dbname);
            }
        }catch(e){
            // console.error(e);
            await this.Connection(dbname);
            return await this.Repository(entities,dbname);
        }
    }
}